package com.ch.mafia.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ch.mafia.base.BaseServlet;
import com.ch.mafia.process.HouseInfoProcess;
import com.ch.mafia.process.PlayerProcess;

/**
 * Servlet implementation class InHouseService
 */
public class InHouseService extends BaseServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public InHouseService() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		JSONObject jsonParams = new JSONObject();
		JSONObject jsonResult = new JSONObject();
		JSONArray jsonArray =new JSONArray();
		try{
			if(request.getParameter("json")!=null){
				jsonParams=new JSONObject(request.getParameter("json"));
				System.out.println("jsonParams:"+jsonParams.toString());
			}
			String houseId = jsonParams.getString("houseid");
			String userId = jsonParams.getString("userid");
			HouseInfoProcess houseInfoProcess =new HouseInfoProcess();
			PlayerProcess playerProcess =new PlayerProcess();
			if(!houseInfoProcess.isFull(houseId)){
				if(houseInfoProcess.isStarted(houseId)){
					jsonResult.put("result",MESSAGE);
					jsonResult.put("message", "游戏已开始");
				}else{
					playerProcess.addPlayer(houseId, userId);
					houseInfoProcess.addHouseNowNum(houseId);
					jsonArray =new JSONArray(playerProcess.getHousePlayer(houseId));
					jsonResult.put("result",SUCCESS);
					jsonResult.put("list", jsonArray);
				}
			}else{
				jsonResult.put("result",MESSAGE);
				jsonResult.put("message", "房间已满");
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			try{
				jsonResult.put("result",FAIL);
			}catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		response.getWriter().print(jsonResult.toString());
	
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
